package com.inight.nightojbackendjudgeservice.judge.codesandbox.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.inight.nightojbackendcommon.common.ErrorCode;
import com.inight.nightojbackendcommon.exception.BusinessException;
import com.inight.nightojbackendjudgeservice.judge.codesandbox.CodeSandbox;
import nightojbackendmodel.codesandbox.ExecuteCodeRequest;
import nightojbackendmodel.codesandbox.ExecuteCodeResponse;


import javax.print.DocFlavor;

/**
 * 远程调用自己的代码沙箱
 */
public class RemoteCodeSandbox implements CodeSandbox {

    private static final String AUTH_REQUEST_HEADER = "auth";
    private static final String AUTH_REQUEST_SECRET = "ying";


    // 远程调用测试
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        // return null;
        System.out.println("调用远程代码沙箱");
        String url = "http://127.0.0.1:8090/executeCode";
        String jsonStr = JSONUtil.toJsonStr(executeCodeRequest);
        String body = HttpUtil.createPost(url)
                .header(AUTH_REQUEST_HEADER, AUTH_REQUEST_SECRET) // 添加请求头
                .body(jsonStr)
                .execute()
                .body();
        if(StrUtil.isBlank(body)) {
            throw new BusinessException(ErrorCode.API_REMOTE_ERROR, "execute code error: " + body);
        }
        return JSONUtil.toBean(body, ExecuteCodeResponse.class);
    }
}
